#include "rtsh.h"

static EditLine *edit;
static History *hist;
static HistEvent hev;

int
main(int argc, char *argv[])
{
   setproctitle("rtsh: %d", getpid());
   if (argc == 1)
      usage();
   else {
      printf("%s\n", argv[0]);
      edit = el_init(__progname, stdin, stdout, stderr);
      if (!edit)
         errx(1, "%s el_init()", __func__);

      hist = history_init();
      if (!hist)
         errx(1, "%s history_init()", __func__);

      _state = (struct rtsh_state *)malloc(sizeof(struct rtsh_state));
      if (!_state) 
         errx(1, "%s malloc()", __func__);

      _state->prompt = (char *)calloc(1, BUFSIZ);
      if (!_state->prompt)
         errx(1, "%s calloc()", __func__);

      history(hist, &hev, H_SETSIZE, MAXHISTORY);
      history(hist, &hev, H_SETUNIQUE, 1);
      el_set(edit, EL_HIST, history, hist);
      el_set(edit, EL_EDITOR, EDITOR);
      el_set(edit, EL_PROMPT, get_prompt);
      el_source(edit, NULL);
      el_set(edit, EL_SIGNAL, 0);

      boolean flag = TRUE;
      const char *buffer;
      size_t length = 0;

      while (flag) {
         buffer = el_gets(edit, (int *)&length);
         if (length > 0) {
            if (strcmp(&buffer[--length], "exit") == 0)
               flag = FALSE;
            else 
               printf("%s", buffer);
         }
         else
            flag = FALSE;
      }

      cleanup();
   }


   return 0;
}

char *
get_prompt()
{
   char hostname[MAXHOSTNAMELEN];
   memset(hostname, '\0', MAXHOSTNAMELEN);

   if (gethostname(hostname, sizeof(hostname)) == 0) {
      char *ptr = strchr(hostname, '.');
      *ptr = '\0';
      snprintf(_state->prompt, BUFSIZ, "%s@%s> ", getlogin(), hostname);
   }
   else 
      snprintf(_state->prompt, BUFSIZ, "router> ");

   return _state->prompt;
}


void
usage(void)
{
   printf("Not implemented yet!\n");
}

void
cleanup()
{

   if (_state) {
      if (_state->prompt)
         free(_state->prompt);

      free(_state);
   }


   if (edit) {
      el_reset(edit);
      el_end(edit);
   }

   if (hist)
      history_end(hist);
}
